//
//  SchoolAddViewController.swift
//  HoneyBee
//
//  Created by point on 2018/1/30.
//  Copyright © 2018年 point. All rights reserved.
//

import UIKit
import MapKit
import SwiftyJSON

class SchoolAddViewController: BaseViewController {
    
    @IBOutlet weak var endView: UIView!
    @IBOutlet weak var telTextField: UITextField!
    @IBOutlet weak var addressDetailTexField: UITextField!
    @IBOutlet weak var addressTextField: UITextField!
    @IBOutlet weak var cityTextField: UITextField!
    @IBOutlet weak var clickBtn: UIButton!
    @IBOutlet weak var schoolStatusSwitch: UISwitch!
    fileprivate var mapView: BMKMapView?
    fileprivate var locationService: BMKLocation?
    fileprivate var mapSearch:BMKGeoCodeSearch?
    fileprivate var locationIndex: Int = 0
    fileprivate var latitudeStr = ""
    fileprivate var longitudeStr = ""
    lazy var locService = BMKLocationManager()
    var userLocation:BMKUserLocation = BMKUserLocation()
    var schoolID:Int = 0
    var type:Int = 0 //0添加 1修改
    
    var currentModel = SchoolDetailModel()
    var currentAddStr:String = ""
    
    
    
    
    @IBOutlet weak var topHeight: NSLayoutConstraint!
    fileprivate lazy var mapCenterPointImageView:UIImageView =  {
        let mapCenterPointImageView = UIImageView()
        mapCenterPointImageView.image = UIImage(named: "mapCenter_point")
        mapCenterPointImageView.isUserInteractionEnabled = true
        return mapCenterPointImageView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        topHeight.constant = LayoutCommon.navHeight + 10
        schoolStatusSwitch.isOn = true
        setupUI()
        loadData()
        postion()
        clickBtn.fastCornerRadius(value: 15)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        mapView?.viewWillAppear()
        mapView?.delegate = self
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        mapView?.viewWillDisappear()
        mapView?.delegate = nil
        mapSearch?.delegate = nil
        
        mapSearch = nil
        locationService = nil
    }
    
    // MARK:- 提交数据
    @IBAction func clickNextBtn(_ sender: UIButton) {
        if telTextField.text?.count == 0 {
            self.hudLoadMessage("检查电话")
            return
        }
        
        if addressTextField.text?.count == 0 {
            self.hudLoadMessage("检查定位")
            return
        }
        
        if addressDetailTexField.text?.count == 0 {
            self.hudLoadMessage("检查地址详情")
            return
        }
        
        
        currentModel.address =  currentAddStr + ";" + addressDetailTexField.text!
        currentModel.latitude = latitudeStr
        currentModel.longitude = longitudeStr
        currentModel.phone = telTextField.text!
        currentModel.isOpen = schoolStatusSwitch.isOn
        
        let institutionId = UserInfo.shareInstance.userModel().institutionId
        
        let current = String().currentTime()
        let dict = [
            "address": currentModel.address,
            "globalAreaCode": currentModel.globalAreaCode,
            "headImg": currentModel.headImg,
            "info": currentModel.info,
            "latitude": currentModel.latitude,
            "longitude": currentModel.longitude,
            "name": currentModel.name,
            "open":  currentModel.isOpen,
            "phone": currentModel.phone,
            "preferential": currentModel.preferential,
            "remark": currentModel.remark,
            "userId": String(UserInfo.shareInstance.userModel().id),
            "id": institutionId != 0 ? institutionId:nil ?? "",
            
            ] as [String : Any]
        
        let api = kHost + kaddInstitution.apiF(time: current, sign: "")
        self.hudLoad()
        TempNetTool.post(api, parameters: dict, progress: nil, success: { [unowned self] (result) in
            self.hudHide()
            let json = JSON(result as Any)
            self.currentModel.id = json["data"]["id"].intValue
            let usermodel = UserInfo.shareInstance.userModel()
            usermodel.institutionId = self.currentModel.id
            UserInfo.shareInstance.setUserModel(model: usermodel)
            if self.type == 0 {
                self.navigationController?.dcPushORPop(self.classForCoder, "SchoolAddSecondViewController",self.currentModel)
                
            }else {
                self.navigationController?.popViewController(animated: true)
            }
        }) { [unowned self] (error) in
            self.hudError()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    func postion()  {
        locService.delegate = self
        locService.coordinateType = BMKLocationCoordinateType.BMK09LL
        locService.desiredAccuracy = kCLLocationAccuracyBest
        locService.activityType = CLActivityType.automotiveNavigation
        locService.pausesLocationUpdatesAutomatically = false
        locService.allowsBackgroundLocationUpdates = false
        locService.locationTimeout = 10
        locService.reGeocodeTimeout = 10
        locService.startUpdatingLocation()
        locService.locatingWithReGeocode = true
        mapView?.showsUserLocation = false
        mapView?.userTrackingMode = BMKUserTrackingModeNone
    }
}

// MARK:- 设置UI
extension SchoolAddViewController {
    func loadData() {
        if UserInfo.shareInstance.userModel().institutionId != 0 {
            self.hudLoad()
            let userModel = UserInfo.shareInstance.userModel()
            let dict = ["userId":userModel.id,
                        "id":userModel.institutionId,
                        "timestamp":"1",
                        "sign":"1",
                        
                        ] as [String : Any]
            TempNetTool.get(kHost + kgetInstitutionInfo, parameters: dict, progress: nil, success: { [weak self ](result) in
                self?.hudHide()
                guard let resultDict = result as? [String : NSObject] else { return }
                guard let data = resultDict["data"] as? [String : NSObject] else { return }
                self?.currentModel = SchoolDetailModel.tmSpeelBreak(data)
                self?.configModel()
            }) { [weak self](error) in
                self?.hudHide()
            }
        }
    }
}


// MARK:- 设置UI
extension SchoolAddViewController {
    func setupUI()  {
        cityTextField.isUserInteractionEnabled = false
        cityTextField.backgroundColor = kColorC2
        addressTextField.isUserInteractionEnabled = false
        addressTextField.backgroundColor = kColorC2
        self.title = "新增机构信息"
        view.backgroundColor = nC1
        clickBtn.layer.cornerRadius = 20
        clickBtn.clipsToBounds = true
        clickBtn.backgroundColor = UIColor.init(hex: "#17bbfe")!
        telTextField.keyboardType = .numberPad
        mapView = BMKMapView(frame:CGRect(x: 10, y: 150, width: kScreenW - 40, height: 155))
        self.endView.addSubview(mapView!)
        //   mapView?.delegate = self
        mapView?.zoomLevel = 19 //显示等级
        mapView?.isZoomEnabled = true //支持缩放
        mapView?.showsUserLocation = false //显示定位的小蓝点
        mapView?.addSubview(mapCenterPointImageView)
        mapCenterPointImageView.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 23, height: 23))
            make.center.equalTo(mapView!);
        }
        
        clickBtn.setTitle(type == 0 ? "下 一 步":"完 成", for: .normal)
    }
    
    func configModel() {
        telTextField.text = self.currentModel.phone
        addressDetailTexField.text = self.currentModel.address.components(separatedBy: ";").last
        schoolStatusSwitch.isOn = self.currentModel.isOpen
    }
}



extension SchoolAddViewController:  BMKMapViewDelegate , BMKLocationManagerDelegate , BMKGeoCodeSearchDelegate {
    func bmkLocationManager(_ manager: BMKLocationManager, didUpdate heading: CLHeading?) {
        mapView?.updateLocationData(userLocation)
    }
    
    func bmkLocationManager(_ manager: BMKLocationManager, didUpdate location: BMKLocation?, orError error: Error?) {
        self.userLocation.location = location!.location
        mapView!.centerCoordinate =  self.userLocation.location.coordinate;
        mapView?.updateLocationData(userLocation)
        locService.stopUpdatingLocation()
    }
    
    func mapView(_ mapView: BMKMapView!, regionDidChangeAnimated animated: Bool) {
        getReverseGeoCodeWithLocation(pt: mapView.region.center)
    }
    
    func getReverseGeoCodeWithLocation(pt:CLLocationCoordinate2D) {
        mapSearch = BMKGeoCodeSearch()
        mapSearch?.delegate = self
        let reverseGeoCodeSearchOption = BMKReverseGeoCodeSearchOption()
        reverseGeoCodeSearchOption.location = pt
        let _ = mapSearch?.reverseGeoCode(reverseGeoCodeSearchOption)
        
    }
    
    func onGetReverseGeoCodeResult(_ searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeSearchResult!, errorCode error: BMKSearchErrorCode) {
        if (error == BMK_SEARCH_NO_ERROR)
        {
            let address = result.addressDetail.district + result.addressDetail.town + result.addressDetail.streetName + result.addressDetail.streetNumber
            cityTextField.text = result.addressDetail.city
            addressTextField.text = address
            latitudeStr = String(result.location.latitude)
            longitudeStr = String(result.location.longitude)
            let arr:[String] = [result.addressDetail.country , result.addressDetail.province ,result.addressDetail.city,result.addressDetail.district,result.addressDetail.town,result.addressDetail.streetName,result.addressDetail.streetNumber,result.addressDetail.adCode]
            currentAddStr = arr.joined(separator: ";")
        }
    }
}

